package com.lagou.controller;

import com.lagou.pojo.AuthCode;
import com.lagou.service.CodeService;
import com.lagou.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Calendar;

/**
 * 验证码微服务控制层类
 */
@RestController
@RequestMapping("/api/code")
public class CodeController {

    @Reference
    private CodeService codeService;

    @Reference
    private EmailService emailService;

    /**
     * 生成验证码并根据邮箱地址发送到对应的邮箱中
     * @param email 邮箱地址
     * @return 操作结果
     */
    @GetMapping("/create/{email}")
    public boolean create(@PathVariable String email) {
        try {
            //保存验证码
            AuthCode authCode = new AuthCode();
            authCode.setEmail(email);
            String code = ((int) ((Math.random() * 9 + 1) * 100000))+"";
            authCode.setCode(code);
            Calendar calendar = Calendar.getInstance();
            authCode.setCreateTime(calendar.getTime());
            calendar.add(Calendar.MINUTE, 10);
            authCode.setExpireTime(calendar.getTime());
            codeService.create(authCode);
            //进行邮件发送
            return emailService.sendEmail(email, code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 校验验证码的方法
     * @param email 邮箱地址
     * @param code 验证码
     * @return 校验结果
     */
    @GetMapping("/validate/{email}/{code}")
    public boolean validate(@PathVariable String email, @PathVariable String code) {
        return codeService.checkAuthCode(email, code);
    }
}
